package org.jeecg.modules.yw.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.service.ISysCategoryService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.yw.entity.*;
import org.jeecg.modules.yw.result.Result;
import org.jeecg.modules.yw.service.*;
import org.jeecg.modules.yw.utils.CommonUtils;
import org.jeecg.modules.yw.utils.DESUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Api(tags="小程序信息查询")
@RestController
@RequestMapping("/app/info")
@Slf4j
public class AppInfoController {
    @Autowired
    private IAttendanceService attendanceService;
    @Autowired
    private IRewardspunishService rewardspunishService;
    @Resource
    private ArticleService articleService;
    @Autowired
    private ISysCategoryService sysCategoryService;
    @Autowired
    private AppointmentService appointmentService;
    @ApiOperation(value = "获取考勤列表")
    @GetMapping(value = "/attendanceByUserId")
    public Result attendanceByUserId(HttpServletRequest request,
                       @RequestParam(name="yearMonth",required = false) String yearMonth) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error("未登录");
        }
        String id = DESUtil.decryptCBCId(token);
        if (id == null) {
            return Result.error("登录已过期");
        }
        QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(yearMonth)) {
            queryWrapper.eq("DATE_FORMAT(attenddate, '%Y-%m')", yearMonth);
        }
        queryWrapper.eq("userId",id);
        queryWrapper.orderByDesc("attenddate");
        return Result.success(attendanceService.list(queryWrapper));
    }
    @ApiOperation(value = "获取奖惩列表")
    @GetMapping(value = "/rewardspunishByUserId")
    public Result rewardspunishByUserId(HttpServletRequest request,
                       @RequestParam(name="type",required = false) String type,
                       @RequestParam(name="pageNo",defaultValue = "1") Integer pageNo,
                       @RequestParam(name="pageSize",defaultValue = "10") Integer pageSize,
                       @RequestParam(name="yearMonth",required = false) String yearMonth) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error("未登录");
        }
        String id = DESUtil.decryptCBCId(token);
        if (id == null) {
            return Result.error("登录已过期");
        }
        QueryWrapper<Rewardspunish> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(yearMonth)) {
            queryWrapper.eq("DATE_FORMAT(rptime, '%Y-%m')", yearMonth);
        }
        if(StringUtils.isNotBlank(type)) {
            queryWrapper.eq("type", type);
        }
        queryWrapper.like("enterid",id);
        queryWrapper.orderByDesc("rptime");
        Page<Rewardspunish> page = new Page<>(pageNo, pageSize);
        return Result.success(rewardspunishService.page(page,queryWrapper));
    }
    @ApiOperation(value = "获取文章列表")
    @GetMapping(value = "/articleByCategory")
    public Result articleByCategory(HttpServletRequest request,
                                        @RequestParam(name="pageNo",defaultValue = "1") Integer pageNo,
                                        @RequestParam(name="pageSize",defaultValue = "10") Integer pageSize,
                                        @RequestParam(name="category") String category) {
//        String token = request.getHeader("token");
//        if (token == null) {
//            return Result.error("未登录");
//        }
//        String id = DESUtil.decryptCBCId(token);
//        if (id == null) {
//            return Result.error("登录已过期");
//        }
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(category)) {
            queryWrapper.eq("category", category);
        }
        queryWrapper.orderByDesc("createtime");
        Page<Article> page = new Page<>(pageNo, pageSize);
        return Result.success(articleService.page(page,queryWrapper));
    }
    @ApiOperation(value = "获取文章信息")
    @GetMapping(value = "/articleById")
    public Result articleById(@RequestParam(name="id") String id) {
//        String token = request.getHeader("token");
//        if (token == null) {
//            return Result.error("未登录");
//        }
//        String id = DESUtil.decryptCBCId(token);
//        if (id == null) {
//            return Result.error("登录已过期");
//        }
        return Result.success(articleService.getById(id));
    }
    @ApiOperation(value = "获取分类字典")
    @GetMapping(value = "/listCategory")
    public Result articleByCategory(HttpServletRequest request,
                                    @RequestParam(name="pid") String pid) {
//        String token = request.getHeader("token");
//        if (token == null) {
//            return Result.error("未登录");
//        }
//        String id = DESUtil.decryptCBCId(token);
//        if (id == null) {
//            return Result.error("登录已过期");
//        }
        QueryWrapper<SysCategory> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(pid)) {
            queryWrapper.eq("pid", pid);
        }
        List<SysCategory> all= new ArrayList<>();
        List<SysCategory> list= sysCategoryService.list(queryWrapper);
        all.addAll(list);
        QueryWrapper<SysCategory> queryWrapper1 = new QueryWrapper<>();
        List<String> parentIdList = new ArrayList<>();
        if (list.size()>0){
            list.forEach(item->{
                parentIdList.add(item.getId());
            });
            queryWrapper1.in("pid",parentIdList);
            if(parentIdList.size()>0) {
                list = sysCategoryService.list(queryWrapper1);
                if (list.size() > 0) {
                    list.forEach(item -> {
                        item.setHasChild("0");
                    });
                }
                all.addAll(list);
            }
        }
        return Result.success(all);
    }
    @ApiOperation(value = "打卡")
    @PostMapping(value = "/kaoqiByOrderid")
    public Result kaoqiByOrderid(@RequestParam("userids")String userids) {
        String[] useridArr = userids.split(",");
        for(String id:useridArr){
            QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userid", id);
            queryWrapper.eq("date_format(attenddate,'yyyy-MM-dd')",DateUtils.getDate("yyyy-MM-dd"));
            Attendance attend = attendanceService.getOne(queryWrapper);
            if(attend!=null){
                attend.setAttendtype(0);
                attendanceService.updateById(attend);
            }else{
                Attendance attendance = new Attendance();
                attendance.setUserid(id);
                attendance.setCreatetime(DateUtils.getDate());
                attendance.setAttendtype(0);
                attendance.setAttenddate(DateUtils.getDate());
                attendance.setId(CommonUtils.getID());
                attendanceService.save(attendance);
            }
        }
        return Result.success();
    }
    @ApiOperation(value = "查看订单是否打卡")
    @PostMapping(value = "/iskaoqi")
    public Result iskaoqi(@RequestParam("orderid")String orderid) {
        List<Appointment> list=appointmentService.list(new QueryWrapper<Appointment>()
                .eq("date_format(createtime,'yyyy-MM-dd')",DateUtils.getDate("yyyy-MM-dd"))
                .eq("orderid",orderid));
        boolean flag=false;
        if(list!=null&&list.size()>0){
            Appointment appointment = list.get(0);
            String bzzid=appointment.getBzzId();
            QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userid", bzzid);
            queryWrapper.eq("date_format(attenddate,'yyyy-MM-dd')",DateUtils.getDate("yyyy-MM-dd"));
            Attendance attend = attendanceService.getOne(queryWrapper);
            if(attend!=null){
                flag=true;
            }
        }
        return Result.success(flag);
    }
}
